package org.ucas.faker.web.annotation;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.ucas.faker.web.entity.Application;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by suemi on 17-7-7.
 */
public class RegistryScanner {

  private static final Logger logger = LogManager.getLogger(RegistryScanner.class);

  static Set<Application> applications = new HashSet<>();

  public static void scanRegistryMethods() {
    logger.info("Application registry scan start!");

    Reflections reflections = new Reflections(new ConfigurationBuilder()
    .setUrls(ClasspathHelper.forPackage("org.ucas.faker.web.controller"))
    .setScanners(new MethodAnnotationsScanner()));
    Set<Method> methods = reflections.getMethodsAnnotatedWith(Registry.class);


      for(Method method:methods) {
        final Registry registry = method.getAnnotation(Registry.class);
        if(registry == null) continue;

        Application app = Application.fromRegistry(registry);
        logger.info(app.getCode());
        final RequestMapping mapping = method.getAnnotation(RequestMapping.class);
        if(mapping != null) {
          final String[] urls = mapping.value();
          if(urls.length > 0) app.setUrl(urls[0]);
        }

        applications.add(app);
      }
    logger.info("Application registry scan completed!");
  }

}
